package com.ly.mpayment.rest.up.util;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import org.mortbay.util.MultiMap;
import org.mortbay.util.UrlEncoded;

import java.util.*;

/**
 * @author luoyang
 * @date 2021/3/24 15:02
 */
public class Util {

    //生成16位唯一性的订单号
    public static String getBatchNO(){
        //随机生成一位整数
        int random = (int) (Math.random()*9+1);
        String valueOf = String.valueOf(random);
        //生成uuid的hashCode值
        int hashCode = UUID.randomUUID().toString().hashCode();
        //可能为负数
        if(hashCode<0){
            hashCode = -hashCode;
        }
        return  valueOf + String.format("%015d", hashCode);
    }

    /**
     * 签名
     * @param jsonObject
     * @param key
     * @return
     */
    private String sign(JSONObject jsonObject, String key){
        //将所有请求的参数放进TreeMap，TreeMap默认按照key升序排列
        //有传的参数才需要签名，比如，充值笔数amt有传的话就要签名，没传的话就不参与签名
        Map<String, String> map = new TreeMap<>();
        for(String s : jsonObject.keySet()){
            map.put(s,jsonObject.getString(s));
        }

        StringBuilder sb = new StringBuilder();
        //循环拼接所有value
        for (String k : map.keySet()) {
            sb.append(map.get(k));
        }
        //最后拼接上秘钥
        sb.append(key);
        System.out.println("签名前：" + sb.toString());
        return MD5.md5(sb.toString());
    }

    public static String toParam(JSONObject jsonObject){
        StringBuilder sb = new StringBuilder();
        for(String s : jsonObject.keySet()){
            sb.append(s);
            sb.append("=");
            sb.append(jsonObject.getString(s));
            sb.append("&");
        }
        return sb.toString().substring(0,sb.toString().lastIndexOf("&"));
    }
    /**
     * 直接失败
     */
    private static Set<String> codesError = new HashSet<String>(){{
        add("10");
        add("11");
    }};

    private static Map<String,String> errorCode = new HashMap<String, String>(){{
        put("1100","CPID错误");
        put("1000","错误的交易类型");
        put("1001","错误的号码运营商");
        put("1002","错误的充值金额");
        put("1003","错误的手机号码");
        put("1004","省份编码错误");
        put("1005","号码与运营商不匹配");
        put("1006","错误的手机归属地");
        put("1007","数字签名错误");
        put("1008","CPID错误");
        //put("1009","重复的订单提交");
        put("1010","CP余额不足");
        put("1011","该地区暂停充值服务");
        put("1012","手机号5分钟内不能重复充值");
        put("1013","充值渠道不合法");
    }};

    public static MultiMap parceString(String str){
        MultiMap map = new MultiMap();
        UrlEncoded.decodeTo(str, map, "utf-8");
        return map;
    }

}
